﻿package fpc.changers;

class AChangerAdapter< T, TAdapted > extends Changer<T>
{
	public function new(changer:Changer < TAdapted >)
	{
		super(onChange);
		
		if (changer != null)
		{
			this.adaptedChanger = changer;
		}
		
		_adapterLevel = 0;
	}
	
	public var adaptedChanger(default, setAdaptedChanger):Changer<TAdapted>;
	function setAdaptedChanger(value)
	{
		if (adaptedChanger != null)
		{
			adaptedChanger.remove(onAdaptedChange);
		}
		
		adaptedChanger = value;
		
		if (value != null)
		{
			value.add(onAdaptedChange);
		}
		return value;
	}
	
	var _adapterLevel:Int;
	
	function onAdaptedChange(value:TAdapted)
	{
		if (_adapterLevel == 0)
		{
			_adapterLevel++;
			this.value = fromAdapted(this.value, value);
			_adapterLevel--;
		}
	}
	
	function onChange(value:T)
	{
		if (adaptedChanger != null && _adapterLevel == 0)
		{
			_adapterLevel++;
			adaptedChanger.value = toAdapted(value, adaptedChanger.value);
			_adapterLevel--;
		}
	}
	
	function fromAdapted(value:T, adaptedValue:TAdapted):T
	{
		return null;
	}
	
	function toAdapted(value:T, adaptedValue:TAdapted):TAdapted
	{
		return null;
	}
}